package com.fps.webshop.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fps.webshop.common.utils.PageUtils;
import com.fps.webshop.common.utils.Query;

import com.fps.webshop.product.dao.CategoryDao;
import com.fps.webshop.product.entity.CategoryEntity;
import com.fps.webshop.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }
    
    @Override
    public List<CategoryEntity> getListToTree() {
        //1.获取所有分类数据
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //2.组装成树形结构
        //2.1).先找到所有的一级分类,然后继续设置分类下的子分类,最后排序，归约
        List<CategoryEntity> firstLevelMenu = categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildrens(categoryEntities, menu));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
        return firstLevelMenu;
    }

    /**
     * 递归设置各级子菜单
     *
     * @param all  所有的分类数据
     * @param root 一级菜单
     * @return
     */
    private List<CategoryEntity> getChildrens(List<CategoryEntity> all, CategoryEntity root) {
        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()) )
                .map(categoryEntity -> {
                    //递归设置子菜单
                    categoryEntity.setChildren(getChildrens(all, categoryEntity));
                    return categoryEntity;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
        return children;
    }
    
    @Override
    public void removeMenusByIds(List<Long> catIds) {
        //todo 如果被删除的分类菜单有被引用，则给出阻拦
        //逻辑删除商品分类
        baseMapper.deleteBatchIds(catIds);
    }

}